<?php

declare(strict_types=1);

namespace App\Command;

use App\Constants\Redis\Region;
use Hyperf\Cache\Annotation\CachePut;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
class GenerateRegionTreeCache extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    protected $redis;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->redis = $this->container->get(RedisFactory::class)->get('default');

        parent::__construct('generateRegionTreeCache');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('生成全国省市树形结构数据');
    }

    public function handle()
    {
        $list = Db::table('region')->whereIn('level', ['1', '2'])->select(['id', 'name', 'pid','level'])->get();
        $tree = $this->tree($list);
        $this->redis->del(Region::TREE);
        $this->redis->set(Region::TREE,json_encode($tree,JSON_UNESCAPED_SLASHES));
    }

    public function tree($list, $pid = 100000,$level = 1)
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item->pid == $pid && $item->level == $level) {
                $children = $this->tree($list, $item->id,$item->level+1);
                $node = [
                    'id' => $item->id,
                    'name' =>$item->name,
                ];
                if(!empty($children)){
                    $node['children'] = $children;
                }
                $tree[] = $node;
            }
        }
        return $tree;
    }
}
